// 模拟常用高阶函数：map、every、some

// map
const map = function (array, fn, context) {
  if (typeof fn !== 'function') {
    throw TypeError(`Uncaught TypeError: ${fn} is not a function`);
  }
  let results = [];
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    results.push(fn.call(context, element, index, array));
  }
  return results;
};

// 测试
// let arr = [1, 2, 3, 4];
// let res = map(
//   arr,
//   function (item, index, array) {
//     console.log(item, index, array, this);
//     return item * item;
//   },
//   { a: 1 },
// );
// console.log(res);

// every
const every = function (array, fn, context) {
  if (typeof fn !== 'function') {
    throw TypeError(`Uncaught TypeError: ${fn} is not a function`);
  }
  let result = true;
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    result = fn.call(context, element, index, array);
    if (result === false) {
      break;
    }
  }
  return result;
};

// 测试
// let arr = [11, 12, 13, 14];
// let res = every(
//   arr,
//   function (item, index, array) {
//     console.log(item, index, array, this);
//     return item > 10;
//   },
//   { a: 1 },
// );
// console.log(res);

// some
const some = function (array, fn, context) {
  if (typeof fn !== 'function') {
    throw TypeError(`Uncaught TypeError: ${fn} is not a function`);
  }
  let result = false;
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    result = fn.call(context, element, index, array);
    if (result) {
      break;
    }
  }
  return result;
};

// 测试
let arr = [1, 3, 5, 9];
let res = some(
  arr,
  function (item, index, array) {
    console.log(item, index, array, this);
    return item % 2 === 0;
  },
  { a: 1 },
);
console.log(res);
